import React from 'react';
import ReactECharts from 'echarts-for-react';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';

interface PieDataItem {
  name: string;
  value: number;
  itemStyle?: {
    color?: string;
  };
}

interface EChartsPieChartProps {
  data: PieDataItem[];
  title?: string;
  height?: number;
}

const EChartsPieChart: React.FC<EChartsPieChartProps> = ({ 
  data, 
  title, 
  height = 300
}) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);

  // 默认颜色数组
  const defaultColors = [
    '#1890ff', '#52c41a', '#722ed1', '#faad14', 
    '#f5222d', '#13c2c2', '#eb2f96', '#73d13d'
  ];

  // 处理数据，添加颜色
  const processedData = data.map((item, index) => ({
    ...item,
    itemStyle: {
      color: item.itemStyle?.color || defaultColors[index % defaultColors.length]
    }
  }));

  // ECharts 饼图配置
  const option = {
    title: {
      text: title,
      textStyle: {
        color: theme.textPrimary,
        fontSize: 16,
        fontWeight: '500'
      },
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      textStyle: {
        color: mode === 'dark' ? '#fff' : '#000'
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'middle',
      textStyle: {
        color: theme.textPrimary
      },
      data: data.map(item => item.name)
    },
    series: [
      {
        name: title || '数据',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: mode === 'dark' ? '#000' : '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            color: theme.textPrimary
          }
        },
        labelLine: {
          show: false
        },
        data: processedData
      }
    ],
    backgroundColor: 'transparent'
  };

  return (
    <div style={{ 
      height, 
      position: 'relative',
      padding: '20px',
      background: theme.cardBackground,
      borderRadius: '8px',
      border: `1px solid ${theme.cardBorder}`,
    }}>
      <ReactECharts 
        option={option} 
        style={{ height: '100%', width: '100%' }}
        theme={mode === 'dark' ? 'dark' : 'light'}
      />
    </div>
  );
};

export default EChartsPieChart;